/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.utils

import java.io.File
import java.util.HashSet
import java.util.Set
import java.util.jar.JarEntry
import java.util.jar.JarFile
import org.apache.commons.io.IOUtils
import org.apache.oro.text.perl.Perl5Util
import org.slf4j.LoggerFactory

class FileUtils {
	static val LOG = LoggerFactory.getLogger(FileUtils);

	private static def void scanning(File file, Set<String> paths) {
		var files = file.listFiles();
		LOG.info(""+files.size)
		for (File cf : files) {
			if (cf.isDirectory) {
				scanning(cf, paths);
			} else if (cf.isFile) {
				var path = cf.absolutePath;
				LOG.info(path);
				paths.add(path);
			}
		}
	}

	def static scanningFile(File file) {
		var paths = new HashSet<String>();
		scanning(file, paths);
		return paths;
	}
	def static scanningJar(File file, String namedPath) {
		if (file.getPath().endsWith(".jar")) {
			var paths = new HashSet<String>();
			try(var jfile = new JarFile(file)) {
				var files = jfile.entries();
				while (files.hasMoreElements()) {
					var JarEntry entry = files.nextElement() as JarEntry;
					if (!entry.isDirectory) {
						var path = entry.getName();
						if (!namedPath.isNullOrEmpty) {
							var p5 = new Perl5Util();
							var named = namedPath.replace("/", "\\/");
							if (p5.match("/" + named + "/", path)) {
								paths.add(path);
							}
						} else {
							paths.add(path);
						}
					}
				}
			}
			return paths;
		}
		return null;
	}
	
	def static readJarClass(File file){
		var mapping = newHashMap();
		try(var jar = new JarFile(file)){
			var entries = jar.entries;
			while(entries.hasMoreElements){
				var entry = entries.nextElement; 
				var name = entry.name;
				if(name.endsWith(".class")){
					var zlass = name.replace(".class","").replaceAll("/",".");
					if(!mapping.containsKey(zlass)){
						var input = jar.getInputStream(entry);
						mapping.put(zlass,IOUtils.toByteArray(input));
					}
				}
			}
		}
		return mapping;
	}

	def static void main(String[] args) {
		println(FileUtils.scanningJar(new File("/home/rcmu/下载/h2-2.1.214.jar"), "META-INF/services"));
	}
}
